package user_v1

import (
	"context"
	"errors"
	"gf-xb-api/internal/dao"
	"gf-xb-api/internal/model/dto"
	"gf-xb-api/internal/model/entity"
	"gf-xb-api/utility/xpermission"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
)

func (s *sUser) Update(ctx context.Context, in *dto.UserUpdateInput) (res bool, err error) {

	cols := dao.SysUser.Columns()

	m := dao.SysUser.Ctx(ctx)

	var user *entity.SysUser
	err = m.Where(cols.Id, in.Id).Scan(&user)
	if err != nil {
		return false, err
	}

	if user == nil {
		return false, errors.New("更新用户失败：用户不存在或已被删除")
	}

	if *user.UpdatedAt != *in.UpdatedAt {
		return false, errors.New("更新用户失败：用户已被更新过，请刷新后重试")
	}

	userUUID := xpermission.GetLoginUserUUID(ctx)

	affected, err := m.Data(g.Map{
		cols.Mobile:    in.Mobile,
		cols.Email:     in.Email,
		cols.Nickname:  in.Nickname,
		cols.UpdatedBy: userUUID,
		cols.UpdatedAt: gtime.Now(),
	}).Where(cols.Id, in.Id).Where(cols.UpdatedAt, in.UpdatedAt).UpdateAndGetAffected()
	if err != nil {
		return false, err
	}

	if affected != 1 {
		return false, errors.New("更新用户失败：未找到用户或者用户已被更新过")
	}

	return true, nil
}
